#include "request.h"




namespace dxy::easyWebServer
{

Request::Request(int fd)
    : m_cliFd(fd)
{

}  

Request::~Request()
{

}

void Request::parse()
{
    parseHead(m_conn.recvLine(m_cliFd));
    while(1)
    {
        std::string line = m_conn.recvLine(m_cliFd);
        if(line == "") break;
        parseMsg(line);
    }
    if(m_method == "POST")
    {
        m_conn.recvMsg(m_cliFd, m_body, atoi(get("Content-Length").c_str()));
    }
}

std::string & Request::get(const std::string & src)
{
    auto it = m_ctx.find(src);
    if(it == m_ctx.end()) throw std::exception();
    return it->second;
}

void Request::set(const std::string & key, const std::string & value)
{
    m_ctx[key] = value;
}

void Request::parseHead(const std::string & src)
{
    std::vector<std::string> tmp;
    splitRegex(tmp, src, " ");
    if(tmp.size() != 3)
    {
        std::__throw_logic_error("parseHead error");
    }
    m_method = tmp[0];
    m_url = tmp[1];
    m_version = tmp[2];
}

void Request::parseMsg(const std::string & src)
{
    std::vector<std::string> tmp;
    splitRegex(tmp, src, ": ");
    if(tmp.size() != 2)
    {
        std::__throw_logic_error("parseHead error");
    }
    m_ctx[tmp[0]] = tmp[1];
}

}

